package SecondeStage.Networkprogramming.TcpFileUpload;

import SecondeStage.Networkprogramming.StreamUtils;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class TcpFileUploadClient {
    public static void main(String[] args) throws Exception {
        // 1.创建客户端,连接服务端
        Socket socket = new Socket(InetAddress.getLocalHost(),8888);
        // 2.创建读取磁盘文件的输入流
        String filePath ="D:\\Java\\JavaProject\\test\\1.jpg";
        BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(filePath));
        // 3.bytes就是文件对应的字节数组
        byte[] bytes = StreamUtils.streamToByteArray(bufferedInputStream);
        // 4.通过socket获取到输出流，将bytes数据发送给服务器
        BufferedOutputStream bufferedOutputStream =new BufferedOutputStream(socket.getOutputStream());
        bufferedOutputStream.write(bytes);
        // 设置写入数据的结束标记
        socket.shutdownOutput();
        // 5.接收从服务端收到的信息
        InputStream inputStream = socket.getInputStream();
        // 使用 StreamUtils 的方法，直接将 inputstream读取到的内容转成字符串
        String s =StreamUtils.streamToString(inputStream);
        System.out.println(s);
        // 6.把不需要再使用的输入流关闭
        bufferedInputStream.close();
    }
}
